import threading
import time

from rich.jupyter import JupyterMixin
from termdb.utils.charts.utils import get_key_thread
from pynput.keyboard import GlobalHotKeys
from pynput import keyboard
import pygetwindow as gw
import sys
import traceback


class Base(JupyterMixin):
    key_bind_functions = {}
    hotkey_bind_functions = {}
    input_bind_functions = None
    current_window_name = gw.getActiveWindow()
    buffer = 1
    live = None
    need_exit = threading.Event()

    def exit(self):
        if self.current_window_name != gw.getActiveWindow():
            return
        self.need_exit.set()

    def loop(self, live):
        self.live = live

        if self.key_bind_functions:
            key_listener = keyboard.Listener(on_press=self.keyboard_press)
            key_listener.daemon = True
            key_listener.start()
            time.sleep(0.2)
        if self.hotkey_bind_functions:
            hotkey_listener = GlobalHotKeys(self.hotkey_bind_functions)
            hotkey_listener.daemon = True
            hotkey_listener.start()
            time.sleep(0.2)
        if self.input_bind_functions:
            input_listener = get_key_thread(self.input_bind_functions, self.live)
            input_listener.daemon = True
            input_listener.start()
        self.need_exit.wait()

    def keyboard_press(self, key: keyboard.Key):
        if self.current_window_name != gw.getActiveWindow():
            return
        if hasattr(key, 'name') and f"<{key.name}>" in self.key_bind_functions:
            self.key_bind_functions[f"<{key.name}>"]()
            try:
                self.live.refresh()
            except BlockingIOError:
                pass
